import time
import socket
import httplib
import requests
requests.packages.urllib3.disable_warnings()

from teye_data.config import cfg
from teye_web.http.URL import URL
from teye_web.http.Request import Request
from teye_web.http.Response import Response, from_requests_response

timeout = 60
socket.setdefaulttimeout(timeout)


class wCurl:
    def __init__(self):
        self._scan_signature = cfg["scan_signature"] if "scan_signature" in cfg else "TScanner/1.0"
        self._scan_cookies = cfg["scan_cookies"] if "scan_cookies" in cfg else {}
        self._scan_proxies = cfg["scan_proxies"] if "scan_proxies" in cfg else {}
        httplib.HTTPConnection.debuglevel = 0

    def get_default_headers(self, headers):
        default_headers = {"User-Agent": self._scan_signature}
        default_headers.update(headers)

        return default_headers

    def get(self, url, headers={}, **kwargs):
        default_headers = self.get_default_headers(headers)
        if not isinstance(url, URL):
            url = URL(url)

        request_response = None
        try:
            request_response = requests.get(url.url_string, headers=default_headers, **kwargs)
        except:
            return self._make_response(request_response, url)
        response = self._make_response(request_response, url)
        return response

    def post(self, url, headers={}, data=None, **kwargs):
        default_headers = self.get_default_headers(headers)
        if not isinstance(url, URL):
            url = URL(url)
        requests_response = None
        try:
            requests_response = requests.post(url.url_string, headers=default_headers, data=data, **kwargs)
        except:
            return self._make_response(requests_response, url)
        response = self._make_response(requests_response, url)
        return response

    def _send_req(self, req):
        pass

    @staticmethod
    def _make_response(resp_from_requests, req_url):
        if resp_from_requests is None:
            response = Response(req_url=req_url)
        else:
            response = from_requests_response(resp_from_requests, req_url)
        return response


wcurl = wCurl()
